import axios from 'axios'
import useLogin from '@/stores/login.js'
import router from '@/router'
import { showFailToast } from 'vant'
import 'vant/es/toast/style'
import i18n from '@/lang/index'

let loadingInstance = null
const $isMobile = Boolean(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))
const t = i18n.global.t

const service = axios.create({
    baseURL: (() => {
        if (localStorage.getItem('isUseLocal')) {
            return 'https://fleetmanagers.net/stage-api/' // 正式环境
            // return 'http://172.16.190.144:8081/' // 王鹏
            //  return 'http://172.16.1.56:8886/stage-api/' // 测试环境
        } else {
            return import.meta.env.VITE_APP_BASE_URL
        }
    })(),
  // baseURL: import.meta.env.VITE_APP_BASE_URL,
  // baseURL: 'http://172.16.1.54:32602/', // 测试环境
  // baseURL: 'http://172.16.190.149:8080/', // 王群
  // baseURL: 'http://172.16.190.100:8081/', // 于海峰
  // baseURL: 'http://172.16.190.28:8080/', // 叶贵明
  // baseURL: 'http://172.16.190.58:8080/', // 林健
  // baseURL: 'http://172.16.190.144:8080/', // 王鹏
  timeout: 60 * 1000
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    const store = useLogin()

    config.headers['Accept-Language'] = localStorage.getItem('lang') || 'zh-CN' // 语言
    config.headers['Platfrom'] = '1' // 客户端
    config.headers['Authorization'] = `Bearer ${store.token}` // token

    // console.log(`config: ${config.url}`, config)

    // loading
    if (config.loading) {
      loadingInstance = ElLoading.service({ fullscreen: true })
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log(`success: ${response.config.url}`, response)
    const store = useLogin()
    const { reset, setLoginDialog } = store

    const { data, config } = response
    if (config.loading && loadingInstance) {
      loadingInstance.close()
    }

    // 文件类型直接下载
    if (response.headers['content-type'] === 'application/x-msdownload') {
      window.fileName = decodeURI(response.headers['content-disposition']?.split(';')[1].split('=')[1])
      return data
    }

    if (response.status === 200) {
      const { code } = data
      if (code && ![200, 601].includes(code)) {
        // 过期
        if (code === 401) {
          if (window._notLoginMsgFlag) {
            //
          } else {
            window._notLoginMsgFlag = true
            setTimeout(() => {
              window._notLoginMsgFlag = false
            }, 2000)

            reset()
            if ($isMobile) {
              showFailToast(t('notLoginMsg'))
              router.push('/login')
            } else {
              ElMessage.warning(t('notLoginMsg'))
              setLoginDialog(true)
            }
          }
        } else {
          if ($isMobile) {
            showFailToast(data.msg || 'Error')
          } else {
            ElMessage.error(data.msg || 'Error')
          }
        }
        return Promise.reject(data)
      }
      return Promise.resolve(data)
    } else {
      if ($isMobile) {
        showFailToast('Error')
      } else {
        ElMessage.error('Error')
      }
      return Promise.reject(data)
    }
  },
  (error) => {
    // console.log(`error: ${error.config.url}`, error)

    const { response, config, message } = error

    if (config.loading && loadingInstance) {
      loadingInstance.close()
    }

    if (response) {
      if ($isMobile) {
        showFailToast(response.statusText || message)
      } else {
        ElMessage.error(response.statusText || message)
      }
      return Promise.reject(response)
    } else {
      if ($isMobile) {
        showFailToast(message)
      } else {
        ElMessage.error(message)
      }
      return Promise.reject(error)
    }
  }
)

export default service
